<template>
  <div class='container'>

    <el-form :model="ruleForm"
             status-icon
             :rules="rules"
             ref="ruleForm"
             label-width="100px"
             class="demo-ruleForm">

      <el-form-item label="用户名"
                    prop="username">
        <el-input type="text"
                  v-model="ruleForm.username"
                  autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码"
                    prop="password">
        <el-input type="password"
                  v-model="ruleForm.password"
                  autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>

import { checkLogin } from '../../api/index'




export default {




  data () {


    var validateUserName = (rule, value, callback) => {

      if (!/^[a-zA-Z]\w+$/.test(value)) return callback(new Error('用户名不能以数字或者特殊符号开头'));
      callback()

    };

    return {
      ruleForm: {
        username: 'admin',
        password: '123456',

      },
      rules: {
        // username  ele  帮你验证的
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' },

          { validator: validateUserName, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' },
          //   { validator: validatePassword, trigger: 'blur' }
        ],

      }
    };
  },
  methods: {
    submitForm (formName) {
      // 登录发送请求逻辑验证抽出去 
      // axios   200    ！=200  return  false 


      this.$refs[formName].validate((valid) => {

        if (valid) {

          // 1 取用户输入的数据 
          // 2  发送请求 
          // 3  拿到后台返回的数据 进行判断 是否登录成功 
          // 4   如果登录成功了 跳转到首页 home /admin   
          // 5   如果 失败了 那么需要给出提示   重新登录   
          checkLogin(this.ruleForm).then(res => {
            console.log(res);

            let { meta: { status, msg }, data } = res;

            console.log(msg);
            if (status != 200) return this.$message.error(msg);

            this.$message.success(msg);
            let { username, token } = data;
            let newObj = { username, token }
            localStorage.setItem('userName', JSON.stringify(newObj))
            this.$router.push('/')











          })





        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //重置功能 
    resetForm (formName) {
      this.$refs[formName].resetFields();
    }
  },

  mounted () {



  }


}
</script>

<style scoped lang="less">
</style>